using System;
using System.Collections.Generic;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;

namespace GoodStuff
{
    public class GoodTextBox : GoodControlContainerBase, IGoodControl
    {

        public GoodTextBox()
        {
            Trace.WriteLine("GoodTextBox constructor called");
            _control = new TextBox();
            _charactersWide = 4;
        }

        override protected void OnVariableChanged(object sender, EventArgs args)
        {
            if (!_updating)
            {
                _updating = true;
                string s = (_variable as GoodVariable<string>).Value;
                if (s != (_control as TextBox).Text)
                    (_control as TextBox).Text = s;
                _updating = false;
            }
        }

        public override void Initialize()
        {
            Trace.WriteLine("Initializing GoodTextBox " + _variable.Name);
            if (!(_variable is GoodVariable<string>))
                throw (new Exception("GoodTextBox must refer to a variable that is a GoodVariable<string>"));

            TextBox control = (_control as TextBox);

            control.TextAlign = HorizontalAlignment.Right;
            _control.Anchor = AnchorStyles.None;
            _control.AutoSize = false;


            // BEGIN: cheezy code block
            Graphics g = _control.CreateGraphics();
            int d = (int)Math.Pow(10, _charactersWide) - 1;
            SizeF t = g.MeasureString(d.ToString(), _control.Font);
            _control.Size = new Size((int)t.Width + 30, _control.Height);
            control.Text = (_variable as GoodVariable<string>).Value;
            // END: cheezy code ends here

            control.TextChanged += OnValueChanged;

            base.Initialize();
        }

        public void OnValueChanged(object sender, EventArgs e)
        {
            if (!_updating)
            {
                _updating = true;
                Trace.WriteLine("GoodTextBox " + _variable.Name + " changed in UI");
                if (_variable != null)
                {
                    (_variable as GoodVariable<string>).Value = ((_control as TextBox).Text);
                }
                _updating = false;
            }
        }
    }
}
